<!--
 * @Description: 描述信息
 * @Version: 版本号
 * @Author: xuebao
 * @Date: 2023-12-05 11:21:23
 * @LastEditors: renmengxue
 * @LastEditTime: 2023-12-08 15:10:30
-->
<template>
  <div class="login-page">
    <ValidateForm @form-submit="onFormSubmit">
      <div class="mb-3">
        <label for="exampleInputEmail1" class="form-label">邮箱地址</label>
        <ValidateInput :rules="emailRules" v-model="emailVal" type="text" placeholder="请输入邮箱地址" />
      </div>
      <div class="mb-3">
        <label for="exampleInputEmail1" class="form-label">密码</label>
        <ValidateInput :rules="passwordRules" v-model="passwordVal" type="password" placeholder="请输入密码" />
      </div>
      <template #submit>
        <span class="btn btn-primary">提交</span>
      </template>
    </ValidateForm>
  </div>
</template>

<script lang='ts'>
import { ref, defineComponent } from 'vue'
import ValidateForm from '../components/ValidateForm.vue'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import CreateMessage from '../components/CreateMessage'
import { useUserStore } from '@/store/user'
export default defineComponent({
  components: {
    ValidateInput,
    ValidateForm
  },
  setup() {
    const store = useStore()
    const userStore = useUserStore()
    const router = useRouter()
    const onFormSubmit = async (result: boolean) => {
      if (result) {
        // const payload = {
        //   email: emailVal.value,
        //   password: passwordVal.value
        // }

        // store.dispatch('loginAndFetch', payload).then(
        //   (data) => {
        //     const cm = CreateMessage('登陆成功2s后跳转', 'success')
        //     setTimeout(() => {
        //       cm.destroy()
        //       router.push('/')
        //     }, 2000)
        //   }).catch(e => {
        //     console.log(e)
        //   })
        try {
          await userStore.login(emailVal.value, passwordVal.value)// login 之后拿token
          await userStore.fetchCurrentUser()// 把token带给axios的headers里面获取用户信息
          CreateMessage('登陆成功2s后跳转', 'success', 2000)
          setTimeout(() => {
            router.push('/')
          }, 2000)
        } catch (error) {
          console.log(error)
        }
      }
    }

    const emailVal = ref('')
    const passwordVal = ref('')
    const emailRules: RulesProp = [
      { type: 'required', message: '电子邮箱地址不能为空' },
      { type: 'email', message: '请输入正确的电子邮箱格式' }
    ]
    const passwordRules: RulesProp = [
      { type: 'required', message: '密码不能为空' },
      { type: 'range', message: '密码至少包含6位', length: 6 }
    ]

    return {
      emailVal,
      passwordVal,
      emailRules,
      passwordRules,
      onFormSubmit
    }
  }

})

</script>

<style scoped></style>
